package First;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

//   参考链接：https://www.jianshu.com/p/db1611a16cb8
public class OntimeSend {
	
	public static String USERNAME = "zlycgbg@163.com";
	public static String PASSWORD = "#xm05910592";
	protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(USERNAME, PASSWORD);
    }
	public static Connection connect(Connection c) {
		try {
			Class.forName("org.sqlite.JDBC");//Administrator
			c = DriverManager.getConnection("jdbc:sqlite:C:/Users/Administrator/MiaoAccount.db");
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			System.exit(0);
		}
		return c;
	}
	public static Map<String, String> emailtipmap() {
		Connection connection = null;
		Statement statement = null;
		Map<String, String> map = new HashMap<>();
		connection = connect(connection);
		ResultSet rs = null;
		try {
			connection.setAutoCommit(false);
			statement = connection.createStatement();
			String sql = "select openid,email,emailtip from users;";
			rs = connection.createStatement().executeQuery(sql);
		    //System.out.println(rs.toString());
			while (rs.next()) {
				if (!hasAccount(rs.getString(1))) {
					//System.out.println(rs.getString(1) + "当天没有记账");
					//System.out.println("email="+rs.getString(2)+" tip="+rs.getString(3));
					String email = null;
					String emailtip = null;
					email = rs.getString(2);
					emailtip = rs.getString(3);
					if (email!=null && !((emailtip.equals("选此不设记账提醒"))||emailtip==null)) {
						//System.out.println(rs.getString(1) + "有设置邮箱提醒"+emailtip);
						map.put(rs.getString(2), rs.getString(3));
						//System.out.println("email="+rs.getString(2)+" tip="+rs.getString(3));
					}
//					else{
//						System.out.println("没有设置邮箱提醒");
//					}
				}
//				else{
//					System.out.println(rs.getString(1) + "当天有记账，不需要提醒");
//				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				statement.close();
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	public static boolean hasAccount(String openid) {
		Connection connection = null;
		connection = connect(connection);
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		String time, sql;
		if (month < 10) {
			time = year + "-0" + month + "-" + day;
		} else {
			time = year + "-" + month + "-" + day;
		}
		sql = "select * from account where openid=" + "\'" + openid + "\'" + " and currenttime like " + "\'" + time
				+ "%\';";
		ResultSet rs = null;
		boolean flag = false;
		try {
			connection.setAutoCommit(false);
			rs = connection.createStatement().executeQuery(sql);
			if (rs.next())
				flag = true;
			else
				flag = false;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				connection.commit();
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return flag;
	}

	@SuppressWarnings("all")
    public static String sendMail(String to, String tip){
    	String user = "zlycgbg@163.com";
		String password = "lyq123";
		String host = "smtp.163.com";
		String from = "zlycgbg@163.com";
		String subject = "喵喵喵记账提醒";
		StringBuffer sb = new StringBuffer();
//		sb.append(tip);
        sb.append("<div style='border:1px solid #d9f4ee;width:500px; height:100px; font-size:20px; line-height:20px; color:#005aa0;padding-left:10px;	padding-top:10px;padding-bottom:20px;'>"+
        		"<h3>喵喵喵记账提醒您：</h3></br><p style='text-indent: 2em;'>"+tip+"&nbsp;&nbsp;(>^ω^<)</p></div><p> <p style='font-size:20px;'></br>注：本邮件为系统提醒，请勿回复，感谢您的支持！</p>");
		String content=sb.toString();
        if (to != null){
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            MailAuthenticator auth = new MailAuthenticator();
            MailAuthenticator.USERNAME = user;
            MailAuthenticator.PASSWORD = password;
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            try {
                MimeMessage message = new MimeMessage(session);
                //message.setFrom(new InternetAddress(from));
                String nick="";    
                nick=javax .mail .internet .MimeUtility .encodeText("微信小程序通知");    
                message.setFrom(new InternetAddress(nick+" <"+from+">"));   
                if (!to.trim().equals(""))
                    message.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(to.trim()));
                message.setSubject(subject);
                MimeBodyPart mbp1 = new MimeBodyPart(); // 正文
                mbp1.setContent(content, "text/html;charset=utf-8");
                Multipart mp = new MimeMultipart(); // 整个邮件：正文+附件
                mp.addBodyPart(mbp1);
                // mp.addBodyPart(mbp2);
                message.setContent(mp);
                message.setSentDate(new Date());
                message.saveChanges();
                Transport trans = session.getTransport("smtp");
                
                trans.send(message);
                //trans.sendMessage(message, message.getAllRecipients());
                System.out.println(message.toString());
            } catch (Exception e){
                e.printStackTrace();
                return "failure";
            }
            return "success";
        }else{  
        	System.out.println("失败了");
            return "failure";
        }
    }
	
		
}